<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Gregwar\Captcha\CaptchaBuilder;

class LoginController extends Controller
{
    //加载登陆表单页
    public function login()
    {
        return view("admin.login.login");
    }
    
    //执行登陆验证
    public function doLogin(Request $request)
    {
        //执行正则验证
        $mycode = session()->get("mycode");
        if($request->input("code")!==$mycode){
            //session()->flash("msg","验证码错误!");
            //return redirect("admin/login");
            
            return back()->with("msg","验证码错误！");
        }
        
        //执行登陆判断
        $email = $request->input("email");
        $password = $request->input("password");
        //获取对应用户信息
        $user = \DB::table("users")->where("email",$email)->first();
        if(!empty($user)){
            //判断密码
            if(md5($password)==$user->password){
                //存储session跳转页面
                session()->set("adminuser",$user);
                return redirect("admin");
               //echo "测试成功!";
            }
        }
        return back()->with("msg","账号或密码错误！");
    }
    
    
    //执行退出方法
    public function logout()
    {
        session()->forget("adminuser");
        return redirect("admin/login");
    }
    
    //验证码的输出
    public function captch($tmp)
    {
        $builder = new CaptchaBuilder;
        $builder->build(120,40);
        
        session()->flash('mycode',$builder->getPhrase()); //存储验证码
        return response($builder->output())->header('Content-type','image/jpeg');
    }
    
}
